BUILD_DIR=./build
IMG_NAME=ChenPuchu_OS.img

ENTRYPOINT:=0x10000

CFLAGS:= -m32
CFLAGS+= -fno-builtin#不需要内置函数
CFLAGS+= -nostdinc#不需要标准头文件
CFLAGS+= -fno-pic#不需要位置无关的代码
CFLAGS+= -fno-pie#不需要位置无关的可执行文件
CFLAGS+= -nostdlib#不需要标准库
CFLAGS+= -fno-stack-protector#不需要栈保护
CFLAGS:=$(strip ${CFLAGS})

DEBUG:= -g
INCLUDE:=-I./include

create_img:
	qemu-img create -f qcow2 $(BUILD_DIR)/$(IMG_NAME) 512M
build_boot:
	mkdir -p $(BUILD_DIR)/boot
	nasm -f bin ./boot/boot.asm -o $(BUILD_DIR)/boot/boot.o
	nasm -f bin ./boot/setup.asm -o $(BUILD_DIR)/boot/setup.o
	dd if=$(BUILD_DIR)/boot/boot.o of=$(BUILD_DIR)/$(IMG_NAME) bs=512 count=1 conv=notrunc
	dd if=$(BUILD_DIR)/boot/setup.o of=$(BUILD_DIR)/$(IMG_NAME) seek=2 bs=512 count=4 conv=notrunc

build_kernel: \
	${BUILD_DIR}/kernel/main.o \
	${BUILD_DIR}/kernel/io.o \
	${BUILD_DIR}/kernel/start.o \
	${BUILD_DIR}/lib/string.o \
	${BUILD_DIR}/kernel/console.o
	mkdir -p $(BUILD_DIR)/kernel
	ld -m elf_i386 -static $^ -o $(BUILD_DIR)/kernel/kernel.bin -Ttext $(ENTRYPOINT)
	objcopy -O binary $(BUILD_DIR)/kernel/kernel.bin $(BUILD_DIR)/kernel/system.bin
	nm $(BUILD_DIR)/kernel/kernel.bin|sort > $(BUILD_DIR)/kernel/system.map
	dd if=$(BUILD_DIR)/kernel/system.bin of=$(BUILD_DIR)/$(IMG_NAME) bs=512 count=500 seek=10 conv=notrunc

${BUILD_DIR}/%.o: ./%.c
	mkdir -p $(dir $@)
	gcc $(CFLAGS) $(DEBUG) $(INCLUDE) -c $< -o $@

${BUILD_DIR}/%.o: ./%.asm
	mkdir -p $(dir $@)
	nasm -f elf32 $(DEBUG) $< -o $@

qemu_debug: ${BUILD_DIR}/${IMG_NAME}
	qemu-system-i386 -name "ChenPuchu" -m 1G -drive file=$(BUILD_DIR)/$(IMG_NAME) -boot d -S -s

qemu: ${BUILD_DIR}/${IMG_NAME}
	qemu-system-i386 -name "ChenPuchu" -m 1G -drive file=$(BUILD_DIR)/$(IMG_NAME) -boot d

clean:
	rm -rf $(BUILD_DIR)/*

build_system: clean create_img build_boot build_kernel

run_system: build_system qemu
debug_system: build_system qemu_debug